package com.shikong.blog.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @description: 登录认证过滤器
 **/
@Slf4j
public class JwtAuthenticationLoginFilter extends AbstractAuthenticationProcessingFilter {

    //构造方法中参数
    private final StringRedisTemplate stringRedisTemplate;
    /**
     * 设置jwt登录认证的访问地址
     * @param stringRedisTemplate
     */
    public JwtAuthenticationLoginFilter(StringRedisTemplate stringRedisTemplate) {

        super(new AntPathRequestMatcher("/login", "POST"));
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {

//        ObjectMapper mapper = new ObjectMapper();
//        JsonNode jsonNode = mapper.readTree(request.getInputStream());
//        System.out.println(jsonNode);
//        String username = jsonNode.get("username").textValue();
//        String password = jsonNode.get("password").textValue();
        /*因为流只能读一次，所以采用缓存的方式传递用户名和密码*/
        String username = stringRedisTemplate.opsForValue().get("username");
        String password = stringRedisTemplate.opsForValue().get("password");

        log.info("==> 用户尝试登录认证，username: {}, password: {}", username, password);
        // 将用户名、密码封装到 Token 中
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                = new UsernamePasswordAuthenticationToken(username, password);
        return getAuthenticationManager().authenticate(usernamePasswordAuthenticationToken);
    }

}
